#include "SoundModuleInc\SoundPlayer.h"

#include <string>
#include <stdio.h>

SoundPlayer::SoundPlayer()
{
	init();
}

SoundPlayer::~SoundPlayer()
{
	release();
}

void SoundPlayer::init()
{
	FMOD::System_Create(&m_system);
	m_system->init(32, FMOD_INIT_NORMAL, 0);

	FMOD::Sound* sound;

	const std::string path = "../Data/SourceSound/piano/";
	const std::string extension = ".mid";

	char* buff = new char[3];

	for(int i = 0; i < 88; i++)
	{
		std::string filePath = path;
		itoa(i, buff, 10);
		filePath += buff;
		filePath += extension;
		m_system->createSound(filePath.c_str(), FMOD_HARDWARE, 0, &sound);
		m_vecSound.push_back(sound);
	}

	m_vecSoundChannel.resize(88, NULL);

	delete[] buff;
}

void SoundPlayer::release()
{
	for(int i = 0; i < 88; i++)
	{
		if(m_vecSoundChannel[i] != NULL)
		{
			m_vecSoundChannel[i]->stop();
			m_vecSoundChannel[i] = NULL;
		}
	}

	for(int i = 0; i < 88; i++)
	{
		m_vecSound[i]->release();
	}

	m_system->close();
	m_system->release();
}

void SoundPlayer::playSound(int index)
{
	FMOD::Channel *channel;

	m_system->playSound(FMOD_CHANNEL_FREE, m_vecSound[index], false, &channel);
	channel->setPosition(480, FMOD_TIMEUNIT_MS);
	m_vecSoundChannel[index] = channel;

	m_system->update();
}

void SoundPlayer::stopSound(int index)
{
	FMOD::Channel *channel = m_vecSoundChannel[index];
	if(channel != NULL)
	{
		channel->stop();
	}
	m_vecSoundChannel[index] = NULL;
}

void SoundPlayer::handleEvent(const PianoKeyEvent& e)
{
	typedef std::vector< std::pair< int, PianoKeyEvent::Event > > PianoKeyEventVec;
	PianoKeyEventVec eventVec = e.getContent();

	PianoKeyEventVec::iterator iter = eventVec.begin();
	for(; iter != eventVec.end(); iter++)
	{
		int key = iter->first;
		PianoKeyEvent::Event event = iter->second;

		switch(event)
		{
		case PianoKeyEvent::RELEASE_KEY:
			stopSound(key);
			break;

		case PianoKeyEvent::PRESS_KEY:
			playSound(key);
			break;

		default:
			break;
		}
	}
}